package com.zktravel;

import java.io.File;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.resource.FileResource;
import org.eclipse.jetty.webapp.WebAppContext;

import com.odianyun.util.date.TimeUtils;

public class WebServer {

	private Server server;

	private int port = 8080;
	private String contextPath;
	private String contextDocBase;
	private String webXml;
	
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public String getContextPath() {
		return contextPath;
	}
	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}
	public String getContextDocBase() {
		return contextDocBase;
	}
	public void setContextDocBase(String contextDocBase) {
		this.contextDocBase = contextDocBase;
	}
	public String getWebXml() {
		return webXml;
	}
	public void setWebXml(String webXml) {
		this.webXml = webXml;
	}
	
	public void start() throws Exception {
		long start = System.currentTimeMillis();
	    server = new Server(port);// 创建jetty web容器
	    
	    WebAppContext webapp = new WebAppContext();// 创建服务上下文
	    
	    webapp.setContextPath(contextPath);
	    webapp.setBaseResource(new FileResource(new File(contextDocBase).toURI().toURL()));
	    webapp.setDescriptor(webXml);
	    webapp.setResourceBase(new File(contextDocBase).toURI().toURL().getPath());
	    
	    HandlerCollection handler = new HandlerCollection();
	    handler.setHandlers(new Handler[]{webapp, new DefaultHandler()});
	    server.setHandler(handler);
	    server.start();// 开启服务
	    
	    while (! server.isStarted()) {
	        Thread.sleep(200);
	    }
	    long now = System.currentTimeMillis();
	    
	    System.out.println("server is started(" + (TimeUtils.getSpentTimeText(now-start)) + ").");
	}
	
	public void stop() throws Exception {
	    if (server != null) {
	        server.stop();
	        server.destroy();
	        server = null;
	    }
	}
    
	public static void main(String[] args) throws Exception {
		WebServer webapp = new WebServer();
		
		String classesFilePath = WebServer.class.getClassLoader().getResource("").getFile();
        File appBase = new File(classesFilePath + "/../../src/main/webapp");
        File webXml = new File(classesFilePath + "/web.xml");
        
        webapp.setContextDocBase(appBase.getPath());
        webapp.setWebXml(webXml.getPath());
        webapp.setContextPath("/zk-shop");
        
        webapp.start();
	}
}
